package com.appkubes.fintech.admin.application.risk.data.fund.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appkubes.fintech.admin.application.risk.data.fund.entity.dto.RiskPortraitDTO;
import com.appkubes.fintech.admin.application.risk.data.fund.entity.dto.SocreDTO;
import com.appkubes.fintech.admin.application.risk.data.fund.dao.RiskFundScoreDao;
import com.appkubes.fintech.admin.application.risk.data.fund.service.ScoreService;
import com.appkubes.fintech.admin.application.risk.data.fund.utils.SignUtil;
import com.appkubes.fintech.admin.application.user.dao.UserBaseInfoDao;
import com.appkubes.fintech.admin.application.risk.data.fund.utils.MyOkHttpUtil;

import com.appkubes.fintech.core.po.FintechRiskFundPortrait;
import com.appkubes.fintech.core.po.FintechRiskFundSocre;
import com.appkubes.fintech.core.po.FintechUserBaseInfo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ScoreServiceImpl implements ScoreService {
    @Value("${fund.score.appKey}")
    private String appKey;

    @Value("${fund.score.appSecret}")
    private String appSecret;

    @Value("${fund.score.scoreUrl}")
    private String scoreUrl;


    @Resource
    private UserBaseInfoDao userBaseInfoDao;

    @Resource
    private RiskFundScoreDao riskFundScoreDao;


    @Override
    public SocreDTO getScore(String userKey){
        //先检查数据库是否有对应的结果有的话，就从数据库取，没有从接口获取
        FintechRiskFundSocre fintechRiskFundSocre = riskFundScoreDao.selectByPrimaryKey(userKey);
        SocreDTO socreDTO= new SocreDTO();
        if(fintechRiskFundSocre!=null){
            socreDTO.setScore(fintechRiskFundSocre.getScore());
            return socreDTO;
        }
        //从接口获取
        FintechUserBaseInfo fintechUserBaseInfo = userBaseInfoDao.selectByPrimaryKey(userKey);
        String timestamp = String.valueOf(System.currentTimeMillis());
        JSONObject paramsJson = new JSONObject();
        paramsJson.put("sign", this.getSign(timestamp));
        paramsJson.put("signParams",  this.getSignParams(timestamp));
        paramsJson.put("phone", fintechUserBaseInfo.getPhone());
        paramsJson.put("name", fintechUserBaseInfo.getRealName());
        paramsJson.put("idcard", fintechUserBaseInfo.getIdentityNum());
        paramsJson.toString();

        try {
            JSONObject jsonObject = this.doPost(paramsJson.toString());
            if (jsonObject.getInteger("code") == 0) {
                JSONObject jsonObjectData = jsonObject.getJSONObject("data");
                socreDTO.setScore(jsonObjectData.getString("score"));
                FintechRiskFundSocre  fundSocre = new FintechRiskFundSocre();
                fundSocre.setUserKey(userKey);
                fundSocre.setScore(jsonObjectData.getString("score"));
                fundSocre.setScoreResult(jsonObject.toJSONString());
                fundSocre.setCreateTime(new Date());
                riskFundScoreDao.insert(fundSocre);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("获取龙井分失败：" + e.getMessage());
        }

        return socreDTO;
    }

    private String getSign(String timestamp){
        Map<String, String> params = new HashMap<>();
        params.put("appKey", appKey);
        params.put("timestamp", timestamp);
        return  SignUtil.sign(params,appSecret);
    }

    private Map<String, String> getSignParams(String timestamp){
        Map<String, String> params = new HashMap<>();
        params.put("appKey", appKey);
        params.put("timestamp", timestamp);
        return params;
    }

    private  JSONObject doPost(String paramsJson) throws Exception {

        Response response = MyOkHttpUtil.post(scoreUrl,paramsJson);
        String str = response.body().string();
        if (!StringUtils.isEmpty(str)) {
            JSONObject jsonObject = JSON.parseObject(str);
            System.out.println(jsonObject);
            if (jsonObject.getInteger("code") != 0) {
                throw new Exception(jsonObject.getString("msg"));
            }
            return jsonObject;
        }
        throw new Exception("获取龙井分失败");
    }








}
